﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using SmartSpace.UI.Silverlight.Dynamic.DynamicRef;
using System.Collections.ObjectModel;
using System.Text;

namespace SmartSpace.UI.Silverlight.Dynamic.Controls
{
    /// <summary>
    /// 编号控件
    /// </summary>
    public partial class CodeControl : UserControl, IAsyncControl
    {
        public string TableName { get; set; }
        public int DictId { get; private set; }
        public string UserName { get; set; }
        public event Action<FrameworkElement> SaveDataComplete;
        public event Action<bool, FrameworkElement> SaveDataFail;
        public event Action<FrameworkElement> GetCodeComplete;

        public CodeControl(string tableName, string userName)
        {
            InitializeComponent();

            TableName = tableName;
            UserName = userName;
        }

        public CodeControl(string tableName, int dictId, string userName)
        {
            InitializeComponent();

            TableName = tableName;
            DictId = dictId;
            UserName = userName;
        }

        #region DependencyProperty

        public string Code
        {
            get { return (string)GetValue(CodeProperty); }
            set { SetValue(CodeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Code.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CodeProperty =
            DependencyProperty.Register("Code", typeof(string), typeof(CodeControl), new PropertyMetadata(default(string), OnCodePropertyChangedCallback));

        static void OnCodePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CodeControl control = d as CodeControl;
            if (control.IsReadOnly)
            {
                control.m_textHeader.Text = (string)e.NewValue;
                control.m_textCode.Text = string.Empty;
                control.m_textCode.Visibility = Visibility.Collapsed;
                control.m_textFooter.Text = string.Empty;
            }
            else
            {
                if (string.IsNullOrEmpty((string)e.NewValue))
                {
                    // 没有编号，获取数据
                    //CodeControlUtil.GetData(control);
                }
                else
                {
                    control.m_textCode.Text = (string)e.NewValue;
                    //CodeControlUtil.GetData(control);
                }
            }
        }

        public IEnumerable CodeSource
        {
            get { return (IEnumerable)GetValue(CodeSourceProperty); }
            set { SetValue(CodeSourceProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CodeSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CodeSourceProperty =
            DependencyProperty.Register("CodeSource", typeof(IEnumerable), typeof(CodeControl), new PropertyMetadata(default(IEnumerable), OnCodeSourcePropertyChangedCallback));

        static void OnCodeSourcePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CodeControl control = d as CodeControl;

            // 没有编号，获取数据
            //ObservableCollection<NumberRules> rules = e.NewValue as ObservableCollection<NumberRules>;
            StringBuilder headerBuilder = new StringBuilder();
            string numberText = string.Empty;
            StringBuilder footerBuilder = new StringBuilder();
            bool isHeader = true;
            //foreach (NumberRules rule in rules)
            //{
            //    if (rule.NumType == NumTypes.UnChange)
            //    {
            //        if (isHeader)
            //        {
            //            headerBuilder.Append(rule.NumValue);
            //        }
            //        else
            //        {
            //            footerBuilder.Append(rule.NumValue);
            //        }
            //    }
            //    else
            //    {
            //        numberText = rule.NumValue;
            //        isHeader = false;
            //    }
            //}

            control.m_textHeader.Text = headerBuilder.ToString();
            control.m_textFooter.Text = footerBuilder.ToString();

            control.m_textCode.Text = numberText;
        }

        public bool IsReadOnly
        {
            get { return (bool)GetValue(IsReadOnlyProperty); }
            set { SetValue(IsReadOnlyProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ItemsSource.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsReadOnlyProperty =
            DependencyProperty.Register("IsReadOnly", typeof(bool), typeof(CodeControl), new PropertyMetadata(default(bool), OnIsReadOnlyPropertyChangedCallback));

        static void OnIsReadOnlyPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CodeControl ctrl = d as CodeControl;
            ctrl.SetReadOnly((bool)e.NewValue);
        }

        #endregion

        /// <summary>
        /// 保存数据
        /// </summary>
        public void SaveData()
        {
            if (IsReadOnly)
            {
                OnSaveComplete();
            }
            else
            {
                bool changed = false;
                try
                {
                    int newNumber = Convert.ToInt32(m_textCode.Text);
                    //ObservableCollection<NumberRules> rules = this.CodeSource as ObservableCollection<NumberRules>;
                    ////判断编号是否变化

                    //foreach (NumberRules rule in rules)
                    //{
                    //    if (rule.NumType == NumTypes.Change && !string.Equals(rule.NumValue,newNumber.ToString()))
                    //    {
                    //        rule.NumValue = newNumber.ToString();
                    //        changed = true;
                    //        break;
                    //    }
                    //}
                }
                catch
                {
                    if (SaveDataFail != null)
                    {
                        SaveDataFail(false, this);
                    }
                    return;
                }

                DataInstance data = this.DataContext as DataInstance;
                if (data.Id == Guid.Empty || changed)
                {
                    //CodeControlUtil.SaveData(this);
                }
                else
                {
                    //直接通知保存成功
                    OnSaveComplete();
                }
            }
        }

        /// <summary>
        /// 保存成功后将编号设置为已使用状态
        /// 同时界面上显示已保存的编号
        /// </summary>
        public void OnSaveComplete()
        {
            if (!IsReadOnly)
            {
                //ObservableCollection<NumberRules> rules = this.CodeSource as ObservableCollection<NumberRules>;
                //StringBuilder numberBuilder = new StringBuilder();
                //foreach (NumberRules rule in rules)
                //{
                //    numberBuilder.Append(rule.NumValue);
                //}

                //this.Code = numberBuilder.ToString();
            }

            if (SaveDataComplete != null)
            {
                SaveDataComplete(this);
            }
        }


        public void OnGetCodeComplete()
        {
            if (GetCodeComplete != null)
            {
                GetCodeComplete(this);
            }
        }

        /// <summary>
        /// 保存失败后提示界面
        /// </summary>
        public void OnSaveFail()
        {
            if (SaveDataFail != null)
            {
                SaveDataFail(false, this);
            }
        }

        private void SetReadOnly(bool isReadOnly)
        {
            m_textCode.IsReadOnly = isReadOnly;
        }
    }
}